/* Copyright Andy Mitchell 2007. No warranties */


function FilterPopupUI(gtdinboxPage, parentPopup){
	this._eventObservers = new EventObservers(this);
	this._gtdinboxPage = gtdinboxPage;
	this._doc = gtdinboxPage.doc;
	this._settings = gtdinboxPage.gtdinboxBrowser.settings;
	this._labels = gtdinboxPage._labels;
	this._parentPopup = parentPopup;
	
	return this;
}

FilterPopupUI.prototype.create = function(elParent, parentSearch, showBasic, showPersonal, inlineTypes, extendTypes){
try{

	this.el = this._doc.createElement("DIV");
		this.el.className = "filter-popup";
	if( elParent ) elParent.appendChild( this.el );
	
	var elClose = this._doc.createElement("IMG");
		elClose.src = "chrome://gtdinbox/content/cross.png";
		elClose.className = "close-button";
		elClose.style.position = "absolute";
		elClose.style.right = "0px";
		elClose.style.top = "0px";
		this._eventObservers.observe(elClose, "mousedown", this.clickClose, false);
	this.el.appendChild(elClose);
	
	var fCreateLineItem = GIPROTOTYPE.bind(this, function(type, search, className, canExtend, innerText, insertBefore){
		var prefix = type? this._settings.labels.types[ type ].prefix : "";
		var el = this._doc.createElement("DIV");
			el.className = "line-item " + (className||"");
		el.innerHTML = innerText;
		if( search ) el.setAttribute("gtdSearch", search);
		el.setAttribute("gtdParentSearch", parentSearch);
		el.setAttribute("gtdShowPersonal", (showPersonal? "1":"") );
		if( type ) el.setAttribute("gtdLabelType", type);
		if( canExtend ){
			el.innerHTML += "<img src='chrome://gtdinbox/content/filter-extend.png' />";
		}
		if( insertBefore ) this.el.insertBefore(el, insertBefore);
		else this.el.appendChild( el )
	});
	var fCreateBreak = GIPROTOTYPE.bind(this, function(insertBefore){
		var el = this._doc.createElement("DIV");
			el.className = "line-break";
		if( insertBefore ) this.el.insertBefore(el, insertBefore);
		else this.el.appendChild( el )
	});
	
	
	if( inlineTypes && inlineTypes.length>0 ){	// Show these types inline
		for( var i = 0; i < inlineTypes.length; i++ ){
			var labels = GIPROTOTYPE.clone(this._labels.getLabelsArray( inlineTypes[i] ));
			if( labels ){
				var prefix = this._settings.labels.types[inlineTypes[i]].prefix;
				if( this._settings.labels.types[inlineTypes[i]].defaults ){	// Re-organise - not very efficient
					var defaults = this._settings.labels.types[inlineTypes[i]].defaults;
					var newlabels = [];
					for( d in defaults ){
						
						for( var j = labels.length - 1; j>=0; j-- ){
							if( labels[j]==(prefix+defaults[d]) ){
								newlabels.push( labels[j] );
								labels.splice(j, 1);
							}
						}
					}
					labels = newlabels.concat(labels);
				}
				if( labels ){
					for( var j = 0; j < labels.length; j++ ){
						fCreateLineItem(inlineTypes[i], GIPROTOTYPE.searchableLabel(labels[j]), "line-item-inline", true, labels[j].replace(prefix,"") );
					}
					fCreateBreak();
				}
			}
		}
	};
	
	if( extendTypes && extendTypes.length>0 ){	// Show these types inline
		for( var i = 0; i < extendTypes.length; i++ ){
			fCreateLineItem(extendTypes[i], null, "line-item-extend", true, "By " + extendTypes[i]);	// TODO language
			fCreateBreak();
		}
	};
	
	if( showBasic || showPersonal ) fCreateBreak(this.el.firstChild);
	if( showBasic ){	// Show 'View' (insert first) and SearchBox (append last)

		if( showPersonal ){
			var fromStr = [];
			var toStr = [];
			var emails = this._gtdinboxPage._environment.emails;
			for( e in emails ){
				fromStr.push("from:" + e);
				toStr.push("to:" + e);
			}
			fCreateLineItem(null, "(" + fromStr.join(" OR ") + ") AND (" + toStr.join(" OR ") + ")", null, null, "Show Personal (From Me)", this.el.firstChild);	// TODO language
		}	

		fCreateLineItem(null, null, null, null, "Show All", this.el.firstChild);	// TODO language
		
		var el = this._doc.createElement("DIV");
			el.className = "search";
			
		el.setAttribute("gtdParentSearch", parentSearch);
		el.innerHTML = "<input type='text' /><button class='filter-search' gtdParentSearchForSearch=\"" + parentSearch.replace(/\"/g, "\\\"") + "\">Search</button>"	// TODO language
		this.el.appendChild(el);
	}
	
	this._parentSearch = parentSearch;
	this._eventObservers.observe( this.el, "mouseup", this.mouseDown, false);
}catch(e){
	if( GTDDEBUGMODE ) alert("filterpopup create\n" + e.toString());
}
	this._popuper = new Popuper(this._gtdinboxPage, this.el, this);
	this._popuper.addEventHandler( this, "popupOff", this.onPopupOff );
	return this;
};

FilterPopupUI.prototype.mouseDown = function(event){
try{
	if( event.button==2 ) return;
	if( event.shiftKey ){	// async
		this.forceOff();
		return;
	}

	// Detect the type (search button, extend button, regular filter)
	var el = GIPROTOTYPE.element(event);
	if( el.nodeName=="BUTTON" ){	// search
		this.clickSearch(el.parentNode.getElementsByTagName("INPUT")[0]);
	}else if( el.nodeName=="IMG" ){	// extend
		this.clickExtend(el.parentNode);
	}else if( el.className.indexOf("line-item")>-1 ){
		this.clickFilter(el);
	}
}catch(e){
	if( GTDDEBUGMODE ) alert("filterpopup mouseDown\n" + e.toString());
}
};


FilterPopupUI.prototype.clickFilter = function(el){
try{
	// Use the line-item to do new search
	this._gtdinboxPage.search( this._parentSearch + " " + (el.getAttribute("gtdSearch")||"") );
	this.forceOff();
}catch(e){
	if( GTDDEBUGMODE ) alert("filterpopup click filter\n" + e.toString());
}
};

FilterPopupUI.prototype.clickExtend = function(el){
	// Use the line-item to generate new popup
	
	if( this._filterChild ){	// turn off
		this._filterChild.destroy();
		this._filterChild = null;
		if( this._filterChildEl==el ) return;
	}
	var parentSearch = this._parentSearch + " " + (el.getAttribute("gtdSearch")||"");
	var extender = (el.className.indexOf("line-item-extend")>-1);
	var showBasic = extender? false:true;
	var showPersonal = (el.getAttribute("gtdShowPersonal")=="1")? true:false;
	var inlineTypes = extender? [el.getAttribute("gtdLabelType")]:[];
	this._filterChild = new FilterPopupUI( this._gtdinboxPage, this ).create(el.ownerDocument.body, parentSearch, showBasic, showPersonal, inlineTypes);
	this._filterChild.popup(el,{location:'right'});
	this._filterChildEl = el;
	this._popuper.addPopupChild(this._filterChild);
};

FilterPopupUI.prototype.clickSearch = function(el){
	// Use the input box to fire a search
	this._gtdinboxPage.search( this._parentSearch + " " + el.value );
	this.forceOff();
};


FilterPopupUI.prototype.forceOff = function(){
	// Find highest FilterPopupUI in chain; and destroy it
	var fp = this;
	while( fp._parentPopup ) fp = fp._parentPopup;
	fp.destroy();
};
FilterPopupUI.prototype.onPopupOff = function(){
	this.destroy();
};
FilterPopupUI.prototype.clickClose = function(){
	this.destroy();
}
FilterPopupUI.prototype.destroy = function(){
	if( !this.el ) return;	// already destroyed
	
	if( this.popupOff ) this.popupOff();
	if( this._popuper ) this._popuper.destroy();
	this._eventObservers.destroy();
	
	if( this.el ) this.el.parentNode.removeChild(this.el);
	this.el = null;
};